package com.xiaoxin.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Slf4j
public class StrUtil {

    private StrUtil() {
    }

    /**
     * 替换字符串中的预留参数
     * 注： 要替换的为  #{参数名} ， #{}也需要替换掉
     */
    public static String replaceParams(String text, Map<String, Object> params) {
        String newText = text;
        if (!CollectionUtils.isEmpty(params)) {
            //k为替换的参数名，v为值
            for (String k : params.keySet()) {
                newText = newText.replace("#{" + k + "}", params.get(k).toString());
            }
        }
        return newText;
    }

    private static final String PLACEHOLDER = "?";

    /**
     * 占位符替换
     *
     * @param str
     * @param args
     * @return
     */
    public static String replace(String str, String... args) {
        for (String arg : args) {
            str = StringUtils.replaceOnce(str, PLACEHOLDER, arg);
        }
        if (str.contains(PLACEHOLDER)) {
            log.error(str);
            throw new IllegalArgumentException();
        }
        return str;
    }

}
